package com.yht.redbook.data.align.consumer;

import com.yht.framework.common.utils.JsonUtils;
import com.yht.redbook.data.align.constant.MQConstants;
import com.yht.redbook.data.align.constant.RedisKeyConstants;
import com.yht.redbook.data.align.constant.TableConstants;
import com.yht.redbook.data.align.domain.mapper.InsertRecordMapper;
import com.yht.redbook.data.align.model.dto.CollectUnCollectNoteMqDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Objects;

@RocketMQMessageListener(consumerGroup = "redbook_group_data_align_" + MQConstants.TOPIC_COUNT_NOTE_COLLECT,
        topic = MQConstants.TOPIC_COUNT_NOTE_COLLECT)
@Component
@Slf4j
public class TodayNoteCollectIncrementData2DBConsumer implements RocketMQListener<String> {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private InsertRecordMapper insertRecordMapper;

    @Value("${table.shards}")
    private int tableShards;

    @Override
    public void onMessage(String body) {
        log.info("## TodayNoteCollectIncrementData2DBConsumer 消费到了 MQ: {}", body);

        CollectUnCollectNoteMqDTO collectUnCollectNoteMqDTO = JsonUtils.parseObject(body, CollectUnCollectNoteMqDTO.class);

        if (Objects.isNull(collectUnCollectNoteMqDTO)) return;

        // 笔记 ID
        Long noteId = collectUnCollectNoteMqDTO.getNoteId();
        // 笔记发布者 ID
        Long noteCreatorId = collectUnCollectNoteMqDTO.getNoteCreatorId();
        // 今日日期
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // -------------------------------------------- 笔记的收藏数变更记录 -----------------------------------------
        // 构建布隆过滤器 Redis KEY
        String bloomUserNoteCollectNoteIdListKey = RedisKeyConstants.buildBloomUserNoteCollectNoteIdListKey(date);

        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setResultType(Long.class);
        script.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/bloom_today_note_collect_check.lua")));
        // 判断收藏数据变更记录是否存在 Redis 中
        Long result = redisTemplate.execute(script, Collections.singletonList(bloomUserNoteCollectNoteIdListKey), noteId);
        // Lua 脚本，添加到布隆过滤器中
        RedisScript<Long> bloomAddScript = RedisScript.of("return redis.call('BF.ADD', KEYS[1], ARGV[1])", Long.class);

        if (Objects.equals(result, 0L)) {
            // 若布隆过滤器中不存在该笔记的收藏记录，才会落库，减小数据库压力
            long noteIdHashKey = noteId % tableShards;

            // 将日增量变更数据写表
            // - t_data_align_note_collect_count_temp_日期_分片序号
            try {
                insertRecordMapper.insert2DataAlignNoteCollectCountTemplate(TableConstants.buildTableNameSuffix(date, noteIdHashKey), noteId);
            } catch (Exception e) {
                log.error("", e);
            }

            // 数据库写入成功后，再添加至布隆过滤器中
            redisTemplate.execute(bloomAddScript, Collections.singletonList(bloomUserNoteCollectNoteIdListKey), noteId);
        }

        // -------------------------------------------- 笔记发布者的收藏数变更记录 -----------------------------------------
        // 构建布隆过滤器 Redis KEY
        String bloomUserNoteCollectUserIdListKey = RedisKeyConstants.buildBloomUserNoteCollectUserIdListKey(date);
        result = redisTemplate.execute(script, Collections.singletonList(bloomUserNoteCollectUserIdListKey), noteCreatorId);

        if (Objects.equals(result, 0L)) {
            long userIdHashKey = noteCreatorId % tableShards;

            // 将日增量变更数据写表
            // - t_data_align_user_collect_count_temp_日期_分片序号
            try {
                insertRecordMapper.insert2DataAlignUserCollectCountTemplate(TableConstants.buildTableNameSuffix(date, userIdHashKey), noteCreatorId);
            } catch (Exception e) {
                log.error("", e);
            }

            // 数据库写入成功后，再添加到布隆过滤器中
            redisTemplate.execute(bloomAddScript, Collections.singletonList(bloomUserNoteCollectUserIdListKey), noteCreatorId);
        }
    }
}
